package lv.solcraft.replication.server.api;

import java.util.List;

import lv.solcraft.replication.server.bdb.Database;
import lv.solcraft.replication.server.bdb.TxTemplateNoResult;
import lv.solcraft.replication.server.dao.OperDataAccess;
import lv.solcraft.replication.server.model.Oper;
import lv.solcraft.replication.server.model.OperId;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sleepycat.je.Transaction;

@Service
public class DeleteOpersCommand {

    private final Database database;
    private OperDataAccess operDataAccess;

    @Autowired
    public DeleteOpersCommand(Database database) {
        this.database = database;
        this.operDataAccess = database.getOperDataAccess();
    }

    protected void doDelete(final OperId operId) {
        Oper oper = operDataAccess.find(operId);
        if (oper == null)
            return;
        oper.delete();
    }

    public final void delete(final OperId operId) {
        new TxTemplateNoResult(database, 5) {
            @Override
            protected void executeInTxNoResult(Transaction tx) throws Exception {
                doDelete(operId);
            }

        }.execute();
    }

    public final void deleteAll() {
        // TODO delete via iteration!
        List<Oper> opers = operDataAccess.findFirst(Integer.MAX_VALUE);
        for (Oper oper : opers) {
            oper.delete();
        }
    }
}
